package com.multi.tool.protostuff;

import com.alibaba.fastjson.JSON;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import lombok.Data;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class ProtolStuffSerializeDemo {

    public static void main(String[] args) {
        Divide divide = new Divide();
        testStringBytesConvert(JSON.toJSONString(divide));
        System.out.println(divide);
        Schema divideSchema = RuntimeSchema.getSchema(Divide.class);
        LinkedBuffer buffer = LinkedBuffer.allocate(512);
        ByteArrayOutputStream byteArrayOutputStream;
        byte[] bytes = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeTo(byteArrayOutputStream, divide, divideSchema, buffer);
            bytes = byteArrayOutputStream.toByteArray();
            System.err.println(String.format("length : %d  value %s" ,bytes.length , new String(bytes)));
            for(byte b: bytes) {
                System.err.print("[" + (char)b + "]");
                System.err.print(b + " ");
            }
            System.out.println("-----");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Lily lily = new Lily();
        ProtostuffIOUtil.mergeFrom(bytes, lily, divideSchema);
        System.err.println(lily);
    }


    /**
     * 测试string与 byte数组转换
     *
     * @param s
     */
    public static void testStringBytesConvert(String s) {
        try {
            byte[] ba = s.getBytes("UTF-8");
            String s_new = new String(ba, "UTF-8");

            System.out.println("原始字符串:\t" + s);
            System.out.println("byte数组地址:\t" + ba);
            String s1 = Arrays.toString(ba);
            System.out.println("输出byte数组:\t" + s1);
            System.out.println("输出byte数组长度:\t" + s1.length());
            System.out.println("转换为字符串:\t" + s_new);
            System.out.println("---------------------------");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

}

@Data
class Divide {
    String name = "divide";
    String age = "a";
    String age1 = "b";
    String age2 = "c";
    String age3 = "d";
    String age4 = "e";
}

@Data
class Lily {
    int age;
    String name;
}



